package com.xwj.back.utils.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.xwj.back.mapper.OrderMapper;
import com.xwj.back.pojo.OrderPay;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class OrderDataListener extends AnalysisEventListener<OrderPay> {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataListener.class);
    private static final int BATCH_COUNT = 8;
    List<OrderPay> list = new ArrayList<>();
    private final OrderMapper orderMapper;


    public OrderDataListener(OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }


    @Override
    public void invoke(OrderPay orderPay, AnalysisContext analysisContext) {
        orderPay.setOrderId(null);
        orderPay.setStatus(false);
        orderPay.setOrderNumber(UUID.randomUUID().toString().substring(0,6));
        orderPay.setCreateTime(new Date());
        list.add(orderPay);
        if(list.size() >= BATCH_COUNT){
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    //存储到数据库
    private void saveData() {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        for (OrderPay orderPay : list) {
            orderMapper.insert(orderPay);
        }
        LOGGER.info("存储数据库成功！");
    }
}
